For this problem set, we'll be using the Jupyter notebook:
Write a function that returns a list of numbers, such that $x_i=i^2$, for $1\leq i \leq n$. Make sure it handles the case where $n<1$ by raising a ValueError
.
In [ ]:
def squares(n):
"""Compute the squares of numbers from 1 to n, such that the
ith element of the returned list equals i^2.
"""
### BEGIN SOLUTION
if n < 1:
raise ValueError("n must be greater than or equal to 1")
return [i ** 2 for i in range(1, n + 1)]
### END SOLUTION
Your function should print [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
for $n=10$. Check that it does:
In [ ]:
squares(10)
In [ ]:
"""Check that squares returns the correct output for several inputs"""
from nose.tools import assert_equal
assert_equal(squares(1), [1])
assert_equal(squares(2), [1, 4])
assert_equal(squares(10), [1, 4, 9, 16, 25, 36, 49, 64, 81, 100])
assert_equal(squares(11), [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121])
In [ ]:
"""Check that squares raises an error for invalid inputs"""
from nose.tools import assert_raises
assert_raises(ValueError, squares, 0)
assert_raises(ValueError, squares, -4)
Using your squares
function, write a function that computes the sum of the squares of the numbers from 1 to $n$. Your function should call the squares
function -- it should NOT reimplement its functionality.
In [ ]:
def sum_of_squares(n):
"""Compute the sum of the squares of numbers from 1 to n."""
### BEGIN SOLUTION
return sum(squares(n))
### END SOLUTION
The sum of squares from 1 to 10 should be 385. Verify that this is the answer you get:
In [ ]:
sum_of_squares(10)
In [ ]:
"""Check that sum_of_squares returns the correct answer for various inputs."""
assert_equal(sum_of_squares(1), 1)
assert_equal(sum_of_squares(2), 5)
assert_equal(sum_of_squares(10), 385)
assert_equal(sum_of_squares(11), 506)
In [ ]:
"""Check that sum_of_squares relies on squares."""
orig_squares = squares
del squares
try:
assert_raises(NameError, sum_of_squares, 1)
except AssertionError:
raise AssertionError("sum_of_squares does not use squares")
finally:
squares = orig_squares
Using LaTeX math notation, write out the equation that is implemented by your sum_of_squares
function.
$\sum_{i=1}^n i^2$